package com.fqgj.xjd.user.common.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zxy
 * @ClassName: WeightRandomHandler
 * @Description: 资金端分配算法(权重随机算法)
 * @date 2017年09月07日 上午11:01:23
 */
public class WeightRandomHandler {

    private static int weightArraySum(Integer[] weightArrays) {
        int weightSum = 0;
        for (int weightValue : weightArrays) {
            weightSum += weightValue;
        }
        return weightSum;
    }

    public static int getWeightRandom(double[] weightArrays) {
        //int weightSum = weightArraySum(weightArrays);
        //double stepWeightSum = 0;
        //for (int i = 0; i < weightArrays.length; i++) {
        //    stepWeightSum += weightArrays[i];
        //    if (Math.random() <= stepWeightSum / weightSum) {
        //        return i;
        //    }
        //}
        //return -1;
        //return (int) (Math.random() * weightArrays.length);


        int random = -1;
        //计算总权重
        double sumWeight = 0;
        for (Double weightArray : weightArrays) {
            sumWeight += weightArray;
        }
        //产生随机数
        double randomNumber;
        randomNumber = Math.random();

        //根据随机数在的区域

        //1 2 3
        //0-1-3-6
        //0-1/6-2/6-1
        double d1 = 0;
        double d2 = 0;
        for (int i = 0; i < weightArrays.length; i++) {
            d1 = d2;
            d2 += weightArrays[i] / sumWeight;
            if (randomNumber >= d1 && randomNumber < d2) {
                random = i;
                break;
            }
        }
        return random;

    }

    public static void main(String[] args) {
        Map<Integer, Integer> stat = new HashMap<Integer, Integer>();
        double[] weightArrays = {1, 2, 3};  // 数组下标是要返回的值，数组值为数组下标的权重
        for (int i = 0; i < 6000000; i++) {
            int weightValue = WeightRandomHandler.getWeightRandom(weightArrays);
            if (weightValue < 0) {
                continue;
            }
            //System.out.println("按权重返回的随机数：" + weightValue);
            if (stat.get(weightValue) == null) {
                stat.put(weightValue, 1);
            } else {
                stat.put(weightValue, stat.get(weightValue) + 1);
            }
        }
        System.out.println(stat);
    }
}
